<?php if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Sales_order extends CI_Controller
{

    function sales_order()
    {
        parent::__construct();
        $this->is_logged_in();
        $this->load->library('session');
        $this->load->library('form_validation');
        $this->load->library('encrypt');
        $this->load->model('mmaster');
        $this->load->model('mservices');
        $this->load->model('mterritory');
        $this->load->model('mpage');
        $this->load->model('msales');
        #$this->mjadwal->saveLog();
        $this->load->helper('url');
        $this->load->library('enc');
        $this->load->library('cfpdf');
        $this->load->helper('date');
    }

    function is_logged_in()
    {
        $is_logged_in = $this->session->userdata('is_logged_in');
        if (!isset($is_logged_in) || $is_logged_in != true) {
            redirect(base_url() . 'index.php/login');
        }
    }

  function index()
  {
    $this->create();
    $template = "shell/smooth";
  }

    function create($proses = "add", $id = "")
    {
      $data['template']       = "shell/smooth";
      $data['main_view']      = "f-sales-order";
      $data['jenis']          = "create";
      $data['proses']         = $proses;
      $data['id']             = $id;
      $cluster_id             = $this->mglobal->user_cluster($this->session->userdata("username"));
      $data['sales']          = $this->msales->getSales($cluster_id);
      $data['cluster']        = $this->msales->getCluster();
      $data['payment_method'] = $this->msales->getPaymentMethod();
        // $cluster_id = $this->mglobal->user_cluster($this);

        #tangani proses save data
        
        //$this->form_validation->set_rules('so_id', 'Sales Order ID', 'required');
        $this->form_validation->set_rules('so_date', 'sales order date', 'required');
        $this->form_validation->set_rules('sales_id', 'sales id', 'required');
        $this->form_validation->set_rules('iccid[]', 'iccid', 'required');
        //$this->form_validation->set_rules('item_code[]', 'kode item', 'required');
        $this->form_validation->set_rules('item_group_name[]', 'nama group item', 'required');
        $this->form_validation->set_rules('item_name[]', 'nama item', 'required');
        $this->form_validation->set_rules('default_price[]', 'default price', 'required|numeric');
        $this->form_validation->set_rules('reseller_disc[]', 'reseller price', 'required|numeric');
        $this->form_validation->set_rules('discount_total', 'total discount', 'required|numeric');
        $this->form_validation->set_rules('cash_paid', 'cash paid', 'required|numeric');
        $this->form_validation->set_rules('scan_in_id', 'Scan In Produk', 'required');
        

        if ($this->form_validation->run() != false) {
			$iccid = $this->input->post('iccid');
            $price = $this->input->post('default_price');
            $discount = $this->input->post('reseller_disc');

            for ($i=0; $i < count($iccid); $i++) { 
                $so_items[] = array("iccid" => $iccid[$i], "price" => $price[$i], "discount" => $discount[$i]);
            }
            $result = $this->_array_distinct($so_items, 'iccid', 'discount', 'other_dup');

            foreach ($result["unique"] as $key) {
                $iccid = $this->_validate_iccid($key["iccid"]);
                if($iccid)
                  { $valid_iccid[] = array("iccid"=>$iccid, "price"=>$key["price"], "discount"=>$key["discount"]); }
            }
            // print_r($valid_iccid);
            $duplicate_iccid = null;
            if(isset($result["duplicate"])) {
                foreach ($result["duplicate"] as $key) {
                    $duplicate_iccid .= $key["iccid"].', '; 
                }
            }
            
            // print_r($valid_iccid); die();

            if(count($valid_iccid)) {
                $data = array(
                    'territory_id' => $cluster_id,
                    'sales_id' => $this->input->post("sales_id"),
                    'so_date' => $this->input->post("so_date"),
                    'cash_paid' => $this->input->post("total"),
                    'discount' => $this->input->post("discount_total"),
                    'payment_method' => $this->input->post("dListPaymentMethod"),
                    'remark' => $this->input->post("remark"),
                    'created_by' => $this->session->userdata('username')
                  );
                // print_r($data);
                // save transaction
                $this->db->trans_begin();
                $so_id = $this->msales->create_so($data);

                foreach ($valid_iccid as $key) {
                    $item_detail = array(
                        'so_id' => $so_id, 
                        'iccid' => $key["iccid"],
                        'price' => $key["price"],
                        'discount' => $key["discount"],
                        "created_by" => $this->session->userdata('username')
                      );
                    
                    $sod_id = $this->msales->so_detail($item_detail);

                }

                // redirect
                if ($this->db->trans_status() === FALSE)
                {
                    $this->db->trans_rollback();
                   $this->session->set_flashdata('message', 'Tidak ada item yang valid, ulangi input ICCID');
                   redirect(base_url() . "index.php/sales_order/create");
                }
                else
                {
                    $this->db->trans_commit();
                    if($duplicate_iccid) { $this->session->set_flashdata('message', 'Data berhasil disimpan dengan nomor transaksi $so_id. Ada duplicate ICCID '.$duplicate_iccid); }
                    else {$message = "Data berhasil disimpan dengan nomor transaksi $so_id" ; }
                    $this->session->set_flashdata('message', $message);
                    redirect(base_url() . "index.php/master/salesOrder ");
                }
            }
            else
            {
                $this->session->set_flashdata('message', 'Semua item sudah dibuat SO sebelumnya. ');
                redirect(base_url().'index.php/sales_order/create');
            }
        }
        $this->load->view($data['template'], $data);
    }
    
    function getDetail($so_id='', $territory_id='')
    {
    	$so_id = $this->enc->defog($so_id);
		$territory_id = $this->enc->defog($territory_id);
				 
        $data['template'] = "shell/smooth";
        $data['main_view'] = "f-sales-order";
        $data['proses'] = 'detail';
        $data['jenis'] = "detail";
        // $data['sales'] = $this->msales->getSales();
        $data['cluster'] = $this->msales->getCluster();
        $data['so_info'] = $this->msales->getById($so_id);
        $data['so_salesName'] = $this->msales->getSalesByOrder($data['so_info']->sales_id);
        // $data['so_detail'] = $this->msales->getSODetail($so_id);
        // echo $data['so_info']->sales_id;
        $data['so_detail'] = $this->msales->salesOrderDetail($data['so_info']->sales_id, $so_id);
        
        // $data['iccid'] = $this->msales->get_iccid();
        $data['payment_method'] = $this->msales->getPaymentMethod();
        
        //$data['sales_order'] = $this->msales->getSalesOrder("adhon");

        $this->load->view($data['template'], $data);
    }

	
	function topdf($so_id='', $territory_id='')
	{	
		//$temp_so_id = $so_id;
//		$temp_territory_id = $territory_id;
//		
//		$fog_so_id = $this->enc->fogit($so_id);
//		$fog_territory_id = $this->enc->fogit($territory_id);
//		
//		if($temp_so_id == $fog_so_id || $temp_territory_id == $fog_territory_id)
//		{
//			$so_id = $this->enc->defog($so_id);
//			$territory_id = $this->enc->defog($territory_id);
//		}
		
		$so_id = $this->enc->defog($so_id);
		$territory_id = $this->enc->defog($territory_id);
		
        //begin configuration
		$textColour = array( 0, 0, 0 );
		$headerColour = array( 100, 100, 100 );
		$tableHeaderTopTextColour = array( 255, 255, 255 );
		$tableHeaderTopFillColour = array( 125, 152, 179 );
		$tableHeaderTopProductTextColour = array( 0, 0, 0 );
		$tableHeaderTopProductFillColour = array( 143, 173, 204 );
		$tableHeaderLeftTextColour = array( 99, 42, 57 );
		$tableHeaderLeftFillColour = array( 184, 207, 229 );
		$tableBorderColour = array( 50, 50, 50 );
		$tableRowFillColour = array( 213, 170, 170 );
		

		$chartColours = array(
						  array( 255, 100, 100 ),
						  array( 100, 255, 100 ),
						  array( 100, 100, 255 ),
						  array( 255, 255, 100 ),
						);

		$data = array(
				  array( 9940, 10100, 9490, 11730 ),
				  array( 19310, 21140, 20560, 22590 ),
				  array( 25110, 26260, 25210, 28370 ),
				  array( 27650, 24550, 30040, 31980 ),
				);
		// End configuration
        
        //distributor Info -- array
        // $dist_info = $this->msales->getDistributor();
        // print_r($dist_info);
        
        //Sales Order Info -- array
        $so_info = $this->msales->getById($so_id);
        $so_salesName = $this->msales->getSalesByOrder($so_info->sales_id);
        $so_detail = $this->msales->generateReport($so_info->sales_id, $so_id);
        $usernamecc = $this->msales->getUsername($this->session->userdata('username'));
        $userIdCa = $this->msales->getca($this->session->userdata('username'));
        $usernameca = $this->msales->getUsername($userIdCa['reporting_to']);
        
       
        $pdf = new FPDF();
		$pdf->AddPage();
        $pdf->SetAutoPageBreak(true, 20);
		// $pdf->SetMargins(0, 20, 20);
		$pdf->AliasNbPages();
        
        
        //header
        
		$pdf->SetFont('Arial','B',14);
		//$this->fpdf->Cell(80);
        $pdf->Ln( 10 );
        $pdf->Cell(70);
		$pdf->Cell(100,-5,"Nota Penjualan",0,1,'L');	
        $pdf->Ln( 5 );

        //table
		$pdf->SetDrawColor( $tableBorderColour[0], $tableBorderColour[1], $tableBorderColour[2] );
		
        //formatting so_id biar banyak 0 nya
        $soid = substr("0000000".$so_info->so_id, -8 );
        
		//Cluster Information		
		$pdf->Ln(8);
		$pdf->SetFont('Arial','',8);		
		//$pdf->Write(19, $dist_info['territory_name']);
        $pdf->Cell( 20, 7, "No Penjualan", 0, 0, 'L', false );
        $pdf->Cell( 10, 7, "   :   ", 0, 0, 'L', false );
        $pdf->Cell( 20, 7, $soid, 0, 1, 'L', false );
        
        $pdf->Cell( 20, 7, "Tanggal", 0, 0, 'L', false );
        $pdf->Cell( 10, 7, "   :   ", 0, 0, 'L', false );
        $pdf->Cell( 20, 7, date('jS, F Y', strtotime($so_info->so_date)), 0, 1, 'L', false );
		
        // $pdf->Cell( 20, 7, "Teritori", 0, 0, 'L', false );
        // $pdf->Cell( 10, 7, "   :   ", 0, 0, 'L', false );
        // $pdf->Cell( 20, 7, $dist_info['territory_name'], 0, 1, 'L', false );
        
        $pdf->Cell( 20, 7, "Nama Sales", 0, 0, 'L', false );
        $pdf->Cell( 10, 7, "   :   ", 0, 0, 'L', false );
        $pdf->Cell( 20, 7, $so_salesName['user_name'], 0, 1, 'L', false );
        
        $pdf->Cell( 20, 7, "NIK", 0, 0, 'L', false );
        $pdf->Cell( 10, 7, "   :   ", 0, 0, 'L', false );
        $pdf->Cell( 20, 7, $so_info->sales_id, 0, 1, 'L', false );
        
		$pdf->SetFont('Helvetica','',10);
		$pdf->Write(19, '');

		//Order Information
		$pdf->Ln( 7 );
		//$pdf->SetTextColor( $tableHeaderTopTextColour[0], $tableHeaderTopTextColour[1], $tableHeaderTopTextColour[2] );
		//$pdf->SetFillColor( $tableHeaderTopFillColour[0], $tableHeaderTopFillColour[1], $tableHeaderTopFillColour[2] );
		$pdf->SetFont( 'Arial', 'B', 8 );
		$pdf->Cell( 10, 8, "No", 1, 0, 'C', false );		
		$pdf->Cell( 20, 8, "Kode Barang", 1, 0, 'C', false );
        // $pdf->Cell( 22, 8, "MDN", 1, 0, 'C', false );		
		$pdf->Cell( 80, 8, "Deskripsi", 1, 0, 'C', false );
        $pdf->Cell( 15, 8, "Jumlah", 1, 0, 'C', false );
        $pdf->Cell( 20, 8, "Satuan (Rp)", 1, 0, 'C', false );
        $pdf->Cell( 20, 8, "Diskon (Rp.)", 1, 0, 'C', false );
        $pdf->Cell( 20, 8, "Total (Rp.)", 1, 1, 'C', false );			
		$pdf->SetFont( 'Arial', '', 8 );
        
        $amount = 0;
        $subtotal = 0;
        
        /** ######################################### BAGIAN DETAIL ORDER ##################################*/
        // print_r($so_detail); die();
        // print_r(array_values($so_detail['kode_barang'])); die();

        if (count($so_detail) > 0)
        {
            $i = 1;
            foreach ($so_detail as $key) {

                    # code...
                    $pdf->Cell( 10, 8, $i++, 1, 0, 'C', false );
                    $pdf->Cell( 20, 8, $key['kode_barang'], 1, 0, 'L', false );
                    // $pdf->Cell( 22, 8, $key['mdn'], 1, 0, 'L', false );
                    // $pdf->MultiCell( 50, 8, $key['deskripsi'], 1, 'L' );    
                    $pdf->Cell( 80, 8, $key['deskripsi'], 1, 0, 'L', false );    
                    
                    // $y = $pdf->GetY();
                    // $pdf->SetXY(122, $y-16);
                    
                    //$pdf->Cell( 50, 10, $so_detail[$jj]['deskripsi'], 0, 0, 'L', false );
                    
                    $pdf->Cell( 15, 8, $key['jumlah'], 1, 0, 'C', false );
                    $pdf->Cell( 20, 8, number_format($key['harga'], 2,',','.'), 1, 0, 'R', false );
                    $pdf->Cell( 20, 8, number_format($key['diskon'], 2,',','.'), 1, 0, 'R', false );
                    $subTotTuple = $key['harga'] * count($key['kode_barang']);
                    $sums = intval($key['jumlah']) * intval($key['harga']);
                    $totTuple = $subTotTuple - $key['diskon'];
                    $pdf->Cell( 20, 8, number_format($sums, 2,',','.'), 1, 1, 'R', false );
                    $subtotal += $totTuple;
                
            }
        }   
                
        /** ------------------------------------------------------------------------------------------------*/
        
        // mencetak 10 baris kalimat dalam variable "teks".
        // $pdf->Ln(12);
        // Select Arial bold 15
        $pdf->SetFont('Arial','',8);
        // Move to the right
        // Framed title

        $pdf->Cell(145); $pdf->Cell(20,7,'Subtotal',1,0,'R');
        $pdf->Cell(20,7,'Rp '.number_format($subtotal, 2,',','.'),1,1,'R');
        $pdf->Cell(145); $pdf->Cell(20,7,'Discount',1,0,'R');
        $pdf->Cell(20,7, number_format($so_info->discount, 2,',','.').'%',1,1,'R');
        $pdf->Cell(145); $pdf->Cell(20,7,'Total',1,0,'R');
        $pdf->Cell(20,7, number_format($so_info->cash_paid, 2,',','.'),1,1,'R');
        $pdf->Cell(145); $pdf->Cell(20,7,'Cash Paid' ,1,0,'R'); 
        $pdf->Cell(20,7,'Rp '.number_format($so_info->cash_paid, 2,',','.'),1,1,'R'); 
        

        // $pdf->Cell(0,8,'Subtotal : Rp '.number_format($subtotal, 2,',','.'),0,1,'R');
        // $pdf->Cell(0,8,'Discount : '.number_format($so_info->discount, 2,',','.').'%',0,1,'R');
        // $pdf->Cell(0,8,'Total : Rp '.number_format($so_info->cash_paid, 2,',','.'),0,1,'R');
        // $pdf->Cell(0,8,'Cash Paid : Rp '.number_format($so_info->cash_paid, 2,',','.'),0,1,'R'); 
        
        	// mencetak 10 baris kalimat dalam variable "teks".
        $pdf->Ln(40);
        // Select Arial bold 15
        $pdf->SetFont('Arial','',8);
        
        
        $pdf->Cell( 70, 8, 'Diterima Oleh,', 0, 0, 'L', false );
        $pdf->Cell( 70, 8, 'Diberikan Oleh,', 0, 0, 'L', false );
        $pdf->Cell( 70, 8, 'Mengetahui CC,', 0, 0, 'L', false );
        
        $pdf->Ln(20);
        
        $pdf->Cell( 70, 8, $usernameca['user_name'], 0, 0, 'L', false );
        $pdf->Cell( 70, 8, $so_salesName['user_name'], 0, 0, 'L', false );
        $pdf->Cell( 70, 8, $usernamecc['user_name'], 0, 0, 'L', false );
        
        // Move to the right
        $pdf->Cell(1);
        // Framed title
        
        $pdf->SetTextColor( $textColour[0], $textColour[1], $textColour[2] );
		$pdf->SetFillColor( $tableRowFillColour[0], $tableRowFillColour[1], $tableRowFillColour[2] );
		
        
        	//Position at 1.5 cm from bottom 
            
        $pdf->SetY(-70);     
        $pdf->Cell(0, 8, "Remarks : ". $so_info->remark, 0, 0, 'L' );
            
		$pdf->SetY(-30); 
		$pdf->Cell(0, 8, "~~ Printed by " . $usernamecc['user_name'] . " ~~", 0, 0, 'C' );
		$pdf->SetFont('Arial','I',8); 
		//Page number 
		$pdf->Cell(10,8,'Page '.$pdf->PageNo().'/{nb}',0,0,'R'); 
		//$pdf->Output();
        
		$pdf->Output();	
	
	}
    
    
    
    function saveSalesOrder()
    {
        $salesOrder = $this->msales->saveSalesOrder();
        
        $so_id = $salesOrder->so_id;
        $iccid = $this->input->post('iccid');
        $item_code = $this->input->post('item_code');
        $item_group_name = $this->input->post('item_group_name');
        $item_name = $this->input->post('item_name');
        $price = $this->input->post('price');
        $discount = $this->input->post('discount');
        
        $count = 0;
        
        for($i = 0; $i < sizeof($iccid); $i++) 
        {
            $this->msales->saveSalesOrderDetail($so_id, $i);   
            $count++;
        }
        echo $count;
    }
    
    function get_iccid_data($iccid, $userid)
    {
        $data['test'] = $this->msales->get_single_iccid($iccid, $userid); //Search DB
        
        if('IS_AJAX')
        {
            echo json_encode($data['test']); //echo json string if ajax request
 
        }
        
    }
    
    function lookup(){
        // process posted form data (the requested items like province)
        $keyword = $this->input->post('term');
        $data['response'] = 'false'; //Set default response
        $query = $this->msales->lookup($keyword); //Search DB
        if( ! empty($query) )
        {
            $data['response'] = 'true'; //Set response
            $data['message'] = array(); //Create array
            foreach( $query as $row )
            {
                $data['message'][] = array(
                                        'id'=> $row->user_id,
                                        'value' => $row->user_name,
                                        'tes' => 'text'
                                     );  //Add a row to array
            }
        }
        if('IS_AJAX')
        {
            echo json_encode($data); //echo json string if ajax request
 
        }
        else
        {
            $this->load->view('sales_order/create',$data); //Load html view of search results
        }
    }
    
        function lookup_iccid(){
        $keyword = $this->input->post('term');
        $data['response'] = 'false'; //Set default response
        $query = $this->msales->lookup_iccid($keyword); //Search DB
        
        if( ! empty($query) )
        {
            $data['response'] = 'true'; //Set response
            $data['message'] = array(); //Create array
            foreach( $query as $row )
            {
                $data['message'][] = array(
                                        'id'=> $row->item_id,
                                        'value' => $row->iccid,
                                        'tes' => 'text'
                                     );  //Add a row to array
            }
        }
        if('IS_AJAX')
        {
            echo json_encode($data); //echo json string if ajax request
 
        }  
    }
    
    function load_sales_order($sales_id){
        // process posted form data (the requested items like province)
        $data['test'] = $this->msales->getSalesOrder($sales_id); //Search DB
        
        if('IS_AJAX')
        {
            echo json_encode($data['test']);
        }
    }
    

  ## validate the Unique ICCIDs before save
  private function _validate_iccid($iccid)
  {
    $status = $this->msales->validate_iccid($iccid);
    if ($status) // if status is true, berarti item sudah ada di SO
      { return false ;}
    else 
      { return $iccid;}
  }

  ## This codes are from PHP-UG Indonesia
  ## Credit By Asmuri Anwar
  ## yaddis@nutech --- 09/29/2012
  private function _array_distinct ($array, $group_keys, $sum_keys = NULL, $count_key = NULL) {
      if (!is_array ($group_keys)) $group_keys = array ($group_keys);
      if (!is_array ($sum_keys)) $sum_keys = array ($sum_keys);

      $existing_sub_keys = array ();
      $output = array ();

      foreach ($array as $key => $sub_array) {
        $puffer = NULL;
        #group keys
        foreach ($group_keys as $group_key){
          $puffer .= $sub_array[$group_key];
        }

        $puffer = serialize ($puffer);
        if (!in_array ($puffer, $existing_sub_keys)){
          $existing_sub_keys[$key] = $puffer;
          $output[$key] = $sub_array;
          // print_r( $output[$key]) ;
        } else {
          $puffer = array_search ($puffer, $existing_sub_keys);
          #sum keys
          foreach ($sum_keys as $sum_key){
            if (is_string ($sum_key)) $output[$puffer][$sum_key] += $sub_array[$sum_key];
          }
          #count grouped keys
          if (!array_key_exists ($count_key, $output[$puffer])) $output[$puffer][$count_key] = 1;
          if (is_string ($count_key)) $output[$puffer][$count_key]++;
        }
      }
      $iccid = array();
      foreach ($output as $so => $val) {
        if(isset($val["other_dup"])) 
        {
            $iccid["duplicate"][] = array( "iccid" => $val["iccid"], "price" => $val["price"], "discount" => $val["discount"] );
        }
        else 
        {
            $iccid["unique"][] = array( "iccid" => $val["iccid"], "price" => $val["price"], "discount" => $val["discount"] );
        }
      }
      return $iccid;
  }
}
